/**
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2009-11 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */
package org.pz.platypus.commandline;

import org.apache.commons.cli.CommandLine;
import org.pz.platypus.GDD;
import org.pz.platypus.exceptions.StopExecutionException;
import org.pz.platypus.utilities.*;

/**
 * Determines the correct output format of the document (based on file extension or command-line option)
 * @author alb
 */
public class FormatSelection
{
    private GDD gdd;
    private CommandLine cl;
    private ClParser clp;
    private String format;

    public FormatSelection(final ClParser ClP, final GDD Gdd)
    {
        clp = ClP;
        cl = ClP.getLine();
        gdd = Gdd;
    }

    /**
     * Determines format of output file and adds it to the sysStrings table.
     * Formats are all in lower case. If no output file and no -format switch is
     * specified by the user, the default is pdf.
     * Fontlist is treated separately in this logic.
     */
    public void determine()
    {
        if( ! cl.hasOption( "-infile" ) && ! cl.hasOption( "-fontlist" )) {
            gdd.log.severe( gdd.getLit( "PLEASE_RERUN_WITH_FILENAMES" ));
            MessagesToUser.showUsage( gdd.lits, clp );
            throw new StopExecutionException( null );
        }

        // if no output format was specified, it defaults to pdf.
        if ( ! cl.hasOption( "-outfile" ) && ! cl.hasOption( "-fontlist" )) {
            String infile = cl.getOptionValue( "infile" );
            String noExtensionName = Filename.getFilenameMinusExtension( infile );
            gdd.sysStrings.add( "_OUTPUT_FILE", noExtensionName + ".pdf" );
            gdd.sysStrings.add( "_FORMAT", "pdf" );
            return;
        }

        if ( cl.hasOption( "-format" )) {
            format = cl.getOptionValue( "format" );
            gdd.sysStrings.add( "_FORMAT", format.toLowerCase() );
            return;
        }

        if ( cl.hasOption( "-fontlist" )) {
            format = "fontlist";
            gdd.sysStrings.add( "_FORMAT", format );
            return;
        }

        String outfileName = cl.getOptionValue( "outfile" );
        format = Filename.getExtension( outfileName );
        if ( format.isEmpty() ) {   // if no output filename extension and no -format switch, warn and use .pdf.
            gdd.log.warning( gdd.getLit( "ERROR.MISSING_FORMAT" ));
            gdd.sysStrings.add( "_OUTPUT_FILE", outfileName + ".pdf" );
            format = ".pdf";
        }
        gdd.sysStrings.add( "_FORMAT", format );
    }
}
